Modeling the Context
Table of Contents
In Haskell, Functor, Applicative, and Monad describe how can we interact with values inside some computational context. The context could mean
- possible failure, modeled by
Maybe a - multiple results, modeled by
[a] - input and output effects, modeled by
IO a - error messages, modeled by
Either e a - async or stateful computations
Functors, Applicatives, and Monads answer the question that how can we interact with values wrapped in the context in different cases.
1. Functor
The central operation is
fmap :: Functor f => (a -> b) -> f a -> f b
(<$>) :: Functor f => (a -> b) -> f a -> f b
fmap applies the function without leaving the context. In brief, we can use Functors when we know how to transform the value, and the context knows how that transformation should be propagated.
2. Applicative
The central operations are
pure :: Applicative f => a -> f a
(<*>) :: Applicative f => f (a -> b) -> f a -> f b
liftA2 :: Applicative f => (a -> b -> c) -> f a -> f b -> f c
Applicative is suitable for combination of several independent fields that may fail, yet requires collective success.
3. Monad
Monad can be used to model that run one contextual computation, inspect its result, and then use it to decide or construct the next computation.
The central operation is
(>>=) :: Monad m => m a -> (a -> m b) -> m b